/*
Copyright 2010 Johan Maasing

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package nu.zoom.android.gdata.project.client.activity;

import java.util.ArrayList;

import nu.zoom.android.gdata.project.client.R;
import nu.zoom.android.gdata.project.client.UIUtilities;
import nu.zoom.android.gdata.project.integration.ProjectHostingClient.Feed;
import android.content.Intent;
import android.os.Bundle;

/**
 * @author Johan Maasing
 * 
 */
public abstract class RetainedListActivity<FeedType extends Feed<RowType>, RowType> extends
		PaginatedListActivity<FeedType, RowType> {

	/**
	 * @param layoutID
	 * @param paginatorID
	 */
	public RetainedListActivity(int layoutID, int paginatorID) {
		super(layoutID, paginatorID);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		@SuppressWarnings("unchecked")
		NonConfigurationInstance retainer = (NonConfigurationInstance) getLastNonConfigurationInstance();
		if (retainer != null) {
			for (RowType item : retainer.data) {
				adapter.add(item);
			}
			numEntries = retainer.numEntries;
			startPosition = retainer.startPosition;
			setPaginatorIndices();
		} else {
			final String action = getIntent().getAction();
			if (action != null) {
				if (Intent.ACTION_VIEW.equalsIgnoreCase(action)) {
					runFeedQuery();
				}
			} else {
				UIUtilities.reportError(this, R.string.error_noaction, null);
				this.finish();
			}
		}
	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		if (adapter != null) {
			final NonConfigurationInstance retainer = new NonConfigurationInstance();
			retainer.data = new ArrayList<RowType>();
			int count = adapter.getCount();
			for (int n = 0; n < count; n++) {
				retainer.data.add(adapter.getItem(n));
			}
			retainer.startPosition = startPosition;
			retainer.numEntries = numEntries;
			return retainer;
		} else {
			return null;
		}
	}

	private class NonConfigurationInstance {
		ArrayList<RowType> data;
		int startPosition;
		int numEntries;
	}
}
